#include "private/table/cxitable_p.h"

#include <QVBoxLayout>

CxiTablePrivate::CxiTablePrivate(CxiTable* p)
	: q_ptr(p)
	  , m_groupProxy(new CxiGroupProxy(nullptr))
	  , m_view(new CxiAdvancedView(p))
	  , m_model(nullptr)
	  , m_proxyFilterModel(new CxiFilterProxy(p))
	  , m_proxySortModel(new CxiSortProxy(p))
{
	//布局设置
	QVBoxLayout* layout = new QVBoxLayout(p);
	layout->setContentsMargins(0, 0, 0, 0);
	layout->setSpacing(0);
	layout->addWidget(m_view);
	m_view->setSortingEnabled(true);
}

CxiTablePrivate::~CxiTablePrivate()
{
	Q_Q(CxiTable);
	delete m_groupProxy;
}

void CxiTablePrivate::setModel(CxiTableModel* model)
{
	if (m_model)
	{
		delete m_model;
	}
	m_model = model;
	m_proxyFilterModel->setSourceModel(m_model);
	m_groupProxy->setSourceModel(m_proxyFilterModel);
	m_proxySortModel->setSourceModel(m_groupProxy);
	m_view->setModel(m_proxyFilterModel);
}

void CxiTablePrivate::setColumnConfigs(const QList<cxitable::GridColumnConfig>& configs)
{
	m_columnConfigs = configs;
	m_view->applyColumnConfig(configs);
}

void CxiTablePrivate::addGroup(const int column, const QString& groupTitle) const
{
	m_groupProxy->addGroupConfig({column, groupTitle});
	updateViewModel();
}

void CxiTablePrivate::addGroups(const QList<cxitable::GroupConfig>& groupConfigs) const
{
	m_groupProxy->addGroupConfigs(groupConfigs);
	updateViewModel();
}

void CxiTablePrivate::removeGroups(const QList<int>& columns) const
{
	m_groupProxy->removeGroupColumns(columns);
	updateViewModel();
}

void CxiTablePrivate::updateViewModel() const
{
	if (m_groupProxy->groupColumns().empty())
	{
		m_view->setModel(m_proxyFilterModel);
	}
	else
	{
		m_view->setModel(m_proxySortModel);
	}
}

void CxiTablePrivate::onFilter(int column, const QString& condition)
{
	m_proxyFilterModel->addFilter(column, condition);
	m_groupProxy->flushGroup();
}

void CxiTablePrivate::clearFilter()
{
	m_proxyFilterModel->clearFilter();
	m_groupProxy->flushGroup();
}